package cn.xiaohaoo.datacollection;

import cn.xiaohaoo.medicine.util.mongo.MongoDatabaseUtils;
import org.bson.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * 数据集下载；http://libproject.hkbu.edu.hk
 */
public class MedicineImgPageProcessor2 implements PageProcessor {
    private static final Logger LOGGER = LoggerFactory.getLogger(MedicineImgPageProcessor2.class);

    @Override
    public void process(Page page) {
        try {
            String name = page.getHtml().$(".text2").xpath("p/text()").get().replace("   ", "").replace(" ", "");
            String img = "http://libproject.hkbu.edu.hk" + page.getHtml().xpath("//*[@id=\"gallery\"]/table[2]/tbody" +
                "/tr/td[2]/table[1]/tbody/tr/td/p" +
                "[2]/img/@src").get().replace("..", "");
            Document document = new Document();
            document.append("name", name);
            document.append("img", img);
            MongoDatabaseUtils.insertDocument(MongoDatabaseUtils.MEDICINE_DETAIL_COLLECTION, document);
//            HttpUtil.downloadFile(img,new File("D:\\data\\"+name+".jpg"));
        } catch (Exception e) {
            LOGGER.error("=====>{}出错了！", page.getUrl());
        }
    }

    @Override
    public Site getSite() {
        return new Site().setRetryTimes(5);
    }

    public static void main(String[] args) {
        LocalDateTime begin = LocalDateTime.now();
        Spider spider = Spider.create(new MedicineImgPageProcessor2());
        for (int i = 1; i <= 420; i++) {
            spider.addUrl("http://libproject.hkbu.edu.hk/was40/detail?lang=chs&record=" + i + "&channelid=47953");
        }
        spider.thread(5).run();
        System.out.println("爬取用时：" + Duration.between(begin, LocalDateTime.now()).toMinutes() + "分钟");
    }
}
